import json
from PyQt5.QtCore import QUrl, Qt
from PyQt5 import uic
from PyQt5.QtWidgets import QButtonGroup, QMessageBox
from peopleSelect import PeopleSelect


# 应急处置训练页面
class Emergency(PeopleSelect):

    def __init__(self, mainWindow):
        super().__init__(mainWindow.ui.emergency, mainWindow)
        # 使用 edited 记录是否编辑详情
        self.edited = False

        # 设置 radioButton 的 buttonGroup
        self.buttonGroup = QButtonGroup()
        self.buttonGroup.addButton(self.ui.escapeRadioButton)
        self.buttonGroup.addButton(self.ui.fireRadioButton)
        self.buttonGroup.addButton(self.ui.fightRadioButton)

        # 详情编辑按钮一开始隐藏
        self.ui.escapeLinkButton.setHidden(True)
        self.ui.fireLinkButton.setHidden(True)
        self.ui.fightLinkButton.setHidden(True)

        #  动作连接函数
        self.buttonGroup.buttonClicked.connect(self.radioChange)
        self.ui.escapeLinkButton.clicked.connect(self.escape)
        self.ui.fireLinkButton.clicked.connect(self.fireSelect)
        self.ui.fightLinkButton.clicked.connect(self.fight)
        self.ui.finishButton.clicked.connect(self.finishEdit)
        self.ui.btn_escapeHistory.clicked.connect(self.escape_history)
        self.ui.btn_fireHistory.clicked.connect(self.fire_history)
        self.ui.btn_fightHistory.clicked.connect(self.fight_history)
        self.ui.btn_monitor.clicked.connect(self.monitor)

    # 加载页面内容
    def loadData(self):
        super().loadData()

    # radioButton变化时执行的函数，将被选中按钮的详情编辑按钮设为可见，其余隐藏
    def radioChange(self):

        # 每当选择的训练发生变化，设置为未编辑详细信息
        self.edited = False

        self.ui.escapeLinkButton.setHidden(True)
        self.ui.fireLinkButton.setHidden(True)
        self.ui.fightLinkButton.setHidden(True)
        if self.ui.escapeRadioButton.isChecked():
            self.ui.escapeLinkButton.setHidden(False)
        elif self.ui.fireRadioButton.isChecked():
            self.ui.fireLinkButton.setHidden(False)
        elif self.ui.fightRadioButton.isChecked():
            self.ui.fightLinkButton.setHidden(False)

    # 加载训练详情编辑页面弹窗
    def loadDetailsPage(self):
        # 根据选择的训练加载不同的页面
        if self.ui.escapeRadioButton.isChecked():
            self.details = uic.loadUi('ui/escapeTrainingDetails.ui')
        elif self.ui.fireRadioButton.isChecked():
            self.details = uic.loadUi('ui/fireTrainingDetails.ui')
        elif self.ui.fightRadioButton.isChecked():
            self.details = uic.loadUi('ui/fightTrainingDetails.ui')
        else:
            return
        # 设置页面格式
        self.details.setWindowFlags(Qt.SplashScreen | Qt.Dialog | Qt.CustomizeWindowHint | Qt.WindowCloseButtonHint)
        if self.mainWindow.isWhite:
            self.details.setStyleSheet("QDialog {background-color: rgb(255, 255, 255);}")
            self.details.frame.setStyleSheet("QFrame {background-color: rgb(245, 245, 245);}\n"
                                             "QLabel {\n"
                                             "    color: black;\n"
                                             "}\n"
                                             "\n"
                                             "QLineEdit {\n"
                                             "    border-radius: 5px;\n"
                                             "    border: 1px solid rgb(210, 210, 210);\n"
                                             "    color: black;\n"
                                             "    background-color: rgb(255, 255, 255);\n"
                                             "    padding-left: 10px;\n"
                                             "}\n"
                                             "QLineEdit:hover {\n"
                                             "    border: 1px solid rgb(85, 170, 255);\n"
                                             "}\n"
                                             "QLineEdit:focus {\n"
                                             "    border: 1px solid rgb(91, 101, 124);\n"
                                             "}\n"
                                             "/* LINE EDIT */\n"
                                             "QSpinBox {\n"
                                             "    border-radius: 5px;\n"
                                             "    border: 1px solid rgb(210, 210, 210);\n"
                                             "    color: black;\n"
                                             "    background-color: rgb(255, 255, 255);\n"
                                             "    padding-left: 10px;\n"
                                             "}\n"
                                             "QSpinBox:hover {\n"
                                             "    border: 1px solid rgb(85, 170, 255);\n"
                                             "}\n"
                                             "QSpinBox:focus {\n"
                                             "    border: 1px solid rgb(91, 101, 124);\n"
                                             "}\n"
                                             "\n"
                                             "/* RADIO BUTTON */\n"
                                             "QRadioButton{\n"
                                             "    color: rgb(0,0,0);\n"
                                             "}\n"
                                             "QRadioButton::indicator {\n"
                                             "    border: 3px solid rgb(210,210,210);\n"
                                             "    width: 15px;\n"
                                             "    height: 15px;\n"
                                             "    border-radius: 10px;\n"
                                             "    background: rgb(230,230,230);\n"
                                             "}\n"
                                             "QRadioButton::indicator:hover {\n"
                                             "    border: 3px solid  rgb(85, 170, 255);\n"
                                             "}\n"
                                             "QRadioButton::indicator:checked {\n"
                                             "    background: 3px solid rgb(85, 170, 255);\n"
                                             "    border: 3px solid rgb(200,200,200);    \n"
                                             "}\n"
                                             "\n"
                                             "QPushButton {\n"
                                             "    border: 2px solid rgb(210, 210, 210);\n"
                                             "    border-radius: 5px;    \n"
                                             "    color:rgb(0,0,0);\n"
                                             "    background-color: rgb(210, 210, 210);\n"
                                             "}\n"
                                             "QPushButton:hover {\n"
                                             "    background-color: rgb(190,190,190);\n"
                                             "    border: 2px solid rgb(180,180,180);\n"
                                             "}\n"
                                             "QPushButton:pressed {    \n"
                                             "    background-color: rgb(200,200,200);\n"
                                             "    border: 2px solid rgb(190,190,190);\n"
                                             "}")
        self.details.submitButton.clicked.connect(self.detailsSubmit)
        self.details.cancelButton.clicked.connect(self.detailsCancel)

    # 设置逃脱训练详情编辑页面的情况
    def escape(self):
        self.loadDetailsPage()
        self.details.exec_()

    # 设置火灾训练那详情编辑页面的情况
    def fireSelect(self):
        self.loadDetailsPage()
        self.details.exec_()

    # 设置地震训练详情编辑页面的情况
    def fight(self):
        self.loadDetailsPage()
        self.details.exec_()

    # 点击提交按钮时执行的函数
    def detailsSubmit(self):
        if self.ui.escapeRadioButton.isChecked():
            self.escapeNum = self.details.box_escape.value()
            self.escapeDescription = self.details.edit_description.text()
            self.ui.textBrowser.append(u"逃脱训练详情编辑完成")
            self.ui.textBrowser.append(u"逃脱人数：" + str(self.escapeNum) + u"人")
            self.ui.textBrowser.append(u"逃脱训练描述：" + str(self.escapeDescription))
            self.ui.textBrowser.append('')

        elif self.ui.fireRadioButton.isChecked():
            self.fireScope = self.details.box_fireScope.value()
            self.personNum = self.details.box_num.value()
            self.decisionMaker = self.details.box_decisionMaker.value()
            self.percentage = self.details.box_percentage.value()
            self.ui.textBrowser.append(u"火灾训练详情编辑完成")
            self.ui.textBrowser.append(u"火势范围为" + str(self.fireScope))
            self.ui.textBrowser.append(u"监狱人数共：" + str(self.personNum) + u"人")
            self.ui.textBrowser.append(u"决策者数量为：" + str(self.decisionMaker) + u"人")
            self.ui.textBrowser.append(u"高认可度决策者比例：" + str(self.percentage) + u"%")
            self.ui.textBrowser.append('')

        elif self.ui.fightRadioButton.isChecked():
            self.fightNum = self.details.box_fight.value()
            self.fightDescription = self.details.edit_description.text()
            self.ui.textBrowser.append(u"打斗训练详情编辑完成")
            self.ui.textBrowser.append(u"参与打斗人数：" + str(self.fightNum) + u"人")
            self.ui.textBrowser.append(u"打斗训练详情描述：" + str(self.fightDescription))
            self.ui.textBrowser.append('')

        self.edited = True
        self.details.close()

    # 训练详情编辑页面取消按钮执行的函数
    def detailsCancel(self):
        self.details.close()

    # 完成编辑按钮执行的函数
    def finishEdit(self):

        # 判断是否已经选择警员参加训练
        if not self.checkSelected():
            ERROR(u"请选择警员")
            return

        # 判断是否已选择训练种类
        if (not self.ui.escapeRadioButton.isChecked()
                and not self.ui.fireRadioButton.isChecked()
                and not self.ui.fightRadioButton.isChecked()):
            ERROR(u"请选择训练种类")
            return

        # 判断是否完成训练详情编辑页面
        if not self.edited:
            ERROR(u"请完成训练详情编辑")
            return

        # 输出训练完成信息
        self.ui.textBrowser.append(u"完成训练编辑")
        names = self.getSelectedNames()
        strNames = ', '.join(list(map(str, names)))
        self.ui.textBrowser.append(u"警员 " + strNames + u"已加入训练")

        if self.ui.escapeRadioButton.isChecked():
            self.ui.textBrowser.append(u"训练内容危：逃脱模拟训练")
            self.ui.textBrowser.append(u"逃脱人数：" + str(self.escapeNum) + u"人")
            self.ui.textBrowser.append(u"逃脱训练描述：" + str(self.escapeDescription))
            self.ui.textBrowser.append('')
            url = '/plans/params/break/create'
            body = {
                'escapeNum': self.escapeNum,
                'description': self.escapeDescription,
                'police_codes': ['001', '002']
            }


        elif self.ui.fireRadioButton.isChecked():
            self.ui.textBrowser.append(u"训练内容为：火灾模拟训练")
            self.ui.textBrowser.append(u"火势范围为：" + str(self.fireScope))
            self.ui.textBrowser.append(u"监狱人数共：" + str(self.personNum) + u"人")
            self.ui.textBrowser.append(u"决策者数量为：" + str(self.decisionMaker) + u"人")
            self.ui.textBrowser.append(u"高认可度决策者比例：" + str(self.percentage) + u"%")
            self.ui.textBrowser.append('')
            url = '/plans/params/fire/create'
            body = {
                "fireRange": self.fireScope,
                "jailPop": self.personNum,
                "decisionNumber": self.decisionMaker,
                "decisionPortaton": self.percentage / 100,
                "police_codes": ["001", "002", "003", "004"]
            }


        elif self.ui.fightRadioButton.isChecked():
            self.ui.textBrowser.append(u"打斗训练详情编辑完成")
            self.ui.textBrowser.append(u"参与打斗人数：" + str(self.fightNum) + u"人")
            self.ui.textBrowser.append(u"打斗训练详情描述：" + str(self.fightDescription))
            self.ui.textBrowser.append('')
            url = '/plans/params/fight/create'
            body = {
                "fightNumber": self.fightNum,
                "description": self.fightDescription,
                "police_codes": ["001", "002", "003", "004"]
            }

        response = self.mainWindow.session.post(
            url=self.mainWindow.emergencyUrl + url,
            headers={
                'Content-type': 'application/json'
            },
            data=json.dumps(body)
        )
        data = json.loads(response.text)
        if data['code'] == 200:
            self.ui.textBrowser.append(u"训练开始成功")
            self.end_training()
            self.removeAllPeople()
            self.mainWindow.session.post(self.mainWindow.url + '/emergency/start')
        else:
            self.ui.textBrowser.append(data['message'])
        self.ui.textBrowser.append('')


    # 跳转到监控页面的实现函数
    def monitor(self):
        self.mainWindow.ui.stackedWidget.setCurrentWidget(self.mainWindow.ui.web.page_widgets)

    def escape_history(self):
        self.mainWindow.web.ui.browser.load(QUrl(self.mainWindow.url + '/emergency_report/report/escape'))
        self.mainWindow.ui.stackedWidget.setCurrentWidget(self.mainWindow.ui.web.page_widgets)

    def fire_history(self):
        self.mainWindow.web.ui.browser.load(QUrl(self.mainWindow.url + '/emergency_report/report/fire'))
        self.mainWindow.ui.stackedWidget.setCurrentWidget(self.mainWindow.ui.web.page_widgets)

    def fight_history(self):
        self.mainWindow.web.ui.browser.load(QUrl(self.mainWindow.url + '/emergency_report/report/fight'))
        self.mainWindow.ui.stackedWidget.setCurrentWidget(self.mainWindow.ui.web.page_widgets)

    # 检查按钮是否可用
    def isEnabled(self):
        return self.ui.finishButton.isEnabled()

    # 在训练开始可编辑时，启用按钮
    def start_training(self):
        self.ui.view_toBeSelected.setEnabled(True)
        self.ui.view_selected.setEnabled(True)
        self.ui.finishButton.setEnabled(True)
        self.ui.escapeRadioButton.setEnabled(True)
        self.ui.fireRadioButton.setEnabled(True)
        self.ui.fightRadioButton.setEnabled(True)
        self.ui.escapeLinkButton.setEnabled(True)
        self.ui.fireLinkButton.setEnabled(True)
        self.ui.fightLinkButton.setEnabled(True)

    # 训练正在进行时或训练结束时，禁用按钮
    def end_training(self):
        self.ui.view_toBeSelected.setEnabled(False)
        self.ui.view_selected.setEnabled(False)
        self.ui.finishButton.setEnabled(False)
        self.ui.escapeRadioButton.setChecked(False)
        self.ui.fireRadioButton.setChecked(False)
        self.ui.fightRadioButton.setChecked(False)
        self.ui.escapeRadioButton.setEnabled(False)
        self.ui.fireRadioButton.setEnabled(False)
        self.ui.fightRadioButton.setEnabled(False)
        self.ui.escapeLinkButton.setHidden(True)
        self.ui.fireLinkButton.setHidden(True)
        self.ui.fightLinkButton.setHidden(True)
        self.ui.escapeLinkButton.setEnabled(False)
        self.ui.fireLinkButton.setEnabled(False)
        self.ui.fightLinkButton.setEnabled(False)

def ERROR(message):
    msg_box = QMessageBox(QMessageBox.Critical, '错误', message)
    msg_box.exec_()
